package com.edu.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.edu.admin.entity.SysAdmin;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.enums.UseTypeEnum;
import com.edu.admin.service.AdminService;
import com.edu.admin.common.RestResult;
import com.edu.admin.vo.AdminVo;
import com.github.pagehelper.PageInfo;

/**
 * 管理员管理
 *  
 * @author Wangjiong
 * 
 */
@RestController
@RequestMapping(value = "/admin", name = "管理员管理")
public class AdminController {
	
	@Autowired
	private AdminService	adminService;
	
	/**
	 *
	 * @apiGroup admin
	 * @api {get} /admin/list  获取管理员列表
	 * @apiVersion 1.0.0
	 * @apiName getAdminList
	 *
	 * @apiParam {String} schoolName 学校名称  required = false
	 * @apiParam {String} adminName 管理员姓名  required = false
	 * @apiParam {String} account 账号  required = false
	 * @apiParam {Long} roleId 角色id  required = false
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "adminId": 1,
		            "account": "admin",
		            "adminName": "超级管理员",
		            "phone": "18612345678",
		            "roleId": 1,
		            "schoolId": 1,
		            "classesId": 1,
		            "fatherId": 0,
		            "provinceCode": "110000",
		            "cityCode": "110100",
		            "districtCode": "110101",
		            "type": 0,
		            "useType": 0,
		            "schoolName": "测试学校",
		            "roleName": "平台管理员",
		            "roleLevel": 0
		        }
		    ]
		}
	 *
	 *
	 */
    @RequestMapping(value = "list", name = "管理员列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/admin/list')")
    public RestResult getAdminList(@RequestParam(name = "schoolName", required = false) String schoolName,
    		@RequestParam(name = "adminName", required = false) String adminName,
    		@RequestParam(name = "account", required = false) String account,
    		@RequestParam(name = "roleId", required = false) Long roleId)
    		throws Exception {
    	
    	List<AdminVo> adminList = adminService.getAdminList(schoolName, adminName, account, roleId);
        
        return RestResult.ok(adminList);
    }
    

    /**
	 *
	 * @apiGroup admin
	 * @api {get} /admin/listAllPage  获取所有管理员列表（包括停用管理员）(分页)
	 * @apiVersion 1.0.0
	 * @apiName getAllAdminListPage
	 *
	 * @apiParam {String} schoolName 学校名称  required = false
	 * @apiParam {String} adminName 管理员姓名  required = false
	 * @apiParam {String} account 账号  required = false
	 * @apiParam {Long} roleId 角色id required = false
	 * @apiParam {Integer} pageNum 页码  required = false
	 * @apiParam {Integer} pageSize 每页记录数  required = false
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 1,
		        "list": [
		            {
		                "adminId": 1,
		                "account": "admin",
		                "adminName": "超级管理员",
		                "phone": "18612345678",
		                "roleId": 1,
		                "schoolId": 1,
		                "classesId": 1,
		                "fatherId": 0,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110101",
		                "type": 0,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "roleName": "平台管理员"
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 10,
		        "startRow": 1,
		        "endRow": 10,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 1,
		        "isFirstPage": true,
		        "isLastPage": false,
		        "hasPreviousPage": false,
		        "hasNextPage": true,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "firstPage": 1,
		        "lastPage": 1
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAllPage", name = "管理员列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/admin/listAllPage')")
    public RestResult getAllAdminListPage(@RequestParam(name = "schoolName", required = false) String schoolName,
			@RequestParam(name = "adminName", required = false) String adminName,
			@RequestParam(name = "account", required = false) String account,
			@RequestParam(name = "roleId", required = false) Long roleId,
    		@RequestParam(name = "pageNum", required = false) Integer pageNum,
			@RequestParam(name = "pageSize", required = false) Integer pageSize) 
			throws Exception {

		PageInfo<AdminVo> pageInfo = adminService.getAllAdminListPage(pageNum,pageSize,schoolName, adminName, account, roleId);
        return RestResult.ok(pageInfo);
    }
    
    
    /**
	 *
	 * @apiGroup admin
	 * @api {get} /admin/listAll  获取所有管理员列表（包括停用管理员）
	 * @apiVersion 1.0.0
	 * @apiName getAllAdminList
	 *
	 * @apiParam {String} schoolName 学校名称  required = false
	 * @apiParam {String} adminName 管理员姓名  required = false
	 * @apiParam {String} account 账号  required = false
	 * @apiParam {Long} roleId 角色id  required = false
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        {
		            "adminId": 1,
		            "account": "admin",
		            "adminName": "超级管理员",
		            "phone": "18612345678",
		            "roleId": 1,
		            "schoolId": 1,
		            "classesId": 1,
		            "fatherId": 0,
		            "provinceCode": "110000",
		            "cityCode": "110100",
		            "districtCode": "110101",
		            "type": 0,
		            "useType": 0,
		            "schoolName": "测试学校",
		            "roleName": "平台管理员"
		        }
		    ]
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAll", name = "管理员列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/admin/listAll')")
    public RestResult getAllAdminList(@RequestParam(name = "schoolName", required = false) String schoolName,
			@RequestParam(name = "adminName", required = false) String adminName,
			@RequestParam(name = "account", required = false) String account,
			@RequestParam(name = "roleId", required = false) Long roleId) 
			throws Exception {

		List<AdminVo> adminList = adminService.getAllAdminList(schoolName, adminName, account, roleId);
        return RestResult.ok(adminList);
    }
    
 
    /**
	 *
	 * @apiGroup admin
	 * @api {post} /admin/save 保存管理员信息
	 * @apiVersion 1.0.0
	 * @apiName save
	 *
	 * @apiParam {SysAdmin} admin 管理员信息
	 * @apiParamExample 请求示例（json）
	 * {
		    "adminName": "管理员1",
		    "phone": "13901234567",
		    "roleId": 1,
		    "schoolId": 1,
		    "classesId": 1,
		    "provinceCode": "110000",
		    "cityCode": "110100",
		    "districtCode": "110108",
		    "type": 0
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "adminId": 3
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "save", name = "保存管理员信息", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/admin/save')")
	public RestResult save(@Valid @RequestBody SysAdmin admin) throws Exception{
		Map<String, Object> result = new HashMap<>();
		
		result = adminService.saveAdmin(admin);
		
		return RestResult.ok(result);
		
	}
	

	/**
	 *
	 * @apiGroup admin
	 * @api {get} /admin/info 获取管理员信息
	 * @apiVersion 1.0.0
	 * @apiName getAdmin
	 *
	 * @apiParam {Long} adminId 管理员id
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "adminId": 1,
		        "account": "admin",
		        "adminName": "超级管理员",
		        "phone": "18612345678",
		        "roleId": 1,
		        "schoolId": 1,
		        "classesId": 1,
		        "fatherId": 0,
		        "provinceCode": "110000",
		        "cityCode": "110100",
		        "districtCode": "110101",
		        "type": 0,
		        "useType": 0,
		        "schoolName": "测试学校",
		        "roleName": "平台管理员"
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "info", name = "管理员信息", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('/admin/info')")
	public RestResult getAdmin(@RequestParam Long adminId) throws Exception{
		AdminVo adminVo = null;
		
		SysAdmin admin = adminService.getAdmin(adminId);
		
		if (admin!=null)
		{
			adminVo = new AdminVo();
			BeanUtils.copyProperties(admin,adminVo);
		}
		
		return RestResult.ok(adminVo);
	}
	
	/**
	 *
	 * @apiGroup admin
	 * @api {post} /admin/resetpassword 重置密码
	 * @apiVersion 1.0.0
	 * @apiName resetAdminPassword
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "adminId": 2
		}
	 *
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/resetpassword" , method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/admin/resetpassword')")
    public RestResult resetAdminPassword(@RequestBody Map<String,Object> dataMap) throws Exception {
  	   
     	Long adminId = MapUtils.getLong(dataMap, "adminId");
     	
     	if (adminId == null || adminId<=0 )
     	{
     		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
     	}
    	    			
    	int isOk = adminService.resetAdminPassword(adminId);
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
	 *
	 * @apiGroup admin
	 * @api {post} /admin/delete 删除管理员
	 * @apiVersion 1.0.0
	 * @apiName deleteAdmin
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "adminId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/delete" , method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/admin/delete')")
    public RestResult deleteAdmin(@RequestBody Map<String,Object> dataMap) throws Exception {
 	   
    	Long adminId = MapUtils.getLong(dataMap, "adminId");
    	
    	if (adminId == null || adminId<=0 )
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    	    			
    	int isOk = adminService.deleteAdmin(adminId);
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
	 *
	 * @apiGroup admin
	 * @api {post} /admin/on 启用管理员
	 * @apiVersion 1.0.0
	 * @apiName onAdmin
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "adminId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/on" , method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/admin/on')")
    public RestResult onAdmin(@RequestBody Map<String,Object> dataMap) throws Exception {
  	   
     	Long adminId = MapUtils.getLong(dataMap, "adminId");
     	
     	if (adminId == null || adminId<=0 )
     	{
     		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
     	}
    	    			
    	int isOk = adminService.useAdmin(adminId,UseTypeEnum.ISUSE.getCode());
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
	 *
	 * @apiGroup admin
	 * @api {post} /admin/off 停用管理员
	 * @apiVersion 1.0.0
	 * @apiName offAdmin
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "adminId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value="/off" , method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/admin/off')")
    public RestResult offAdmin(@RequestBody Map<String,Object> dataMap) throws Exception {
  	   
     	Long adminId = MapUtils.getLong(dataMap, "adminId");
     	
     	if (adminId == null || adminId<=0 )
     	{
     		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
     	}
    	    			
    	int isOk = adminService.useAdmin(adminId,UseTypeEnum.NOTUSE.getCode());
    	if (isOk>0)
		{
			return RestResult.ok();
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
	 * 修改密码
	 * 
	 * @apiGroup admin
	 * @api {post} /admin/updatepwd 修改密码
	 * @apiVersion 1.0.0
	 * @apiName updatePassword
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "adminId": 2,
		    "oldPassword": "123456",
		    "newPassword": "123"
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
	@RequestMapping(value = "updatepwd", name = "修改密码", method = RequestMethod.POST)
	public RestResult updatePassword(@RequestBody Map<String,Object> dataMap) throws Exception{
		
		Long adminId = MapUtils.getLong(dataMap,"adminId");
		
		String oldPassword = MapUtils.getString(dataMap,"oldPassword");
		
		String newPassword = MapUtils.getString(dataMap,"newPassword");
		
		int isOk = adminService.updatePassword(adminId, oldPassword, newPassword);
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
		
	}


}
